package org.rasterfun.utils

import drag.NavigationMixin
import javax.swing.JPanel
import org.rasterfun.{ArrayGenerator, ArrayBackedImage}
import java.awt.{Image, Graphics}

/**
 * Renders an ArrayGenerator to a JPanel.
 * 
 * @author Hans Haggstrom
 */
class RasterPanel extends JPanel with NavigationMixin {

  private var generator: ArrayGenerator = null
  private var arrayImage: ArrayBackedImage = null
  private var coordinates: Rectangle = null
  private var recalculate = true

  def this(generator: ArrayGenerator) {
    this()
    setGenerator(generator)
  }

  // TODO: Listen to resizes and change image size

  def getGenerator: ArrayGenerator = generator

  def setGenerator(g: ArrayGenerator) {
    generator = g;
    arrayImage = new ArrayBackedImage(getWidth, getHeight)
    recalculate = true
    repaint()
  }

  override def paintComponent(g: Graphics) {
    if (generator != null) {

      if (arrayImage == null || arrayImage.sizeX != getWidth || arrayImage.sizeY != getHeight) {
        arrayImage = new ArrayBackedImage(getWidth, getHeight)
        recalculate = true
      }

      if (coordinates == null) {
        coordinates = Rectangle(-1, -1, 2, 2)
        recalculate = true
      }

      if (recalculate) {
        // Only generate if size or projection changed
        generator.generate(arrayImage, coordinates)
        recalculate = false
      }

      g.drawImage(arrayImage.getImage, 0, 0, null)
    }
  }

  override def onProjectionUpdated(xOffs: Float, yOffs: Float, xScale: Float, yScale: Float) {
    coordinates = Rectangle(xOffs*xScale, yOffs*yScale, xScale, yScale)
    recalculate = true
    repaint()
  }


}

